import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/address.dart';
import 'package:mall/core/providers/pages/mine/address/address_sms_model.dart';
import 'package:mall/core/providers/pages/mine/address/address_update_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/address/address_region_page.dart';
import 'package:mall/components/count_down_text.dart';
import 'package:provider/provider.dart';

class AddressEditPageArgs {
  final bool needVerifyCode;
  final Address address;

  AddressEditPageArgs(this.needVerifyCode, this.address);
}

class AddressEditPage extends StatelessWidget {
  static const routeName = '/AddressEditPage';
  final AddressEditPageArgs args;

  AddressEditPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => AddressUpdateModel(context.read<Api>(), args.address),
        ),
        ChangeNotifierProvider(create: (context) => AddressSmsModel(context.read<Api>()))
      ],
      child: Consumer<AddressUpdateModel>(
        builder: (context, model, child) {
          return Form(
            child: Scaffold(
              appBar: AppBar(
                title: Text(model.address == null ? '新增地址' : '修改地址'),
                actions: <Widget>[
                  Builder(
                    builder: (context) {
                      return IconButton(
                        onPressed: () => _addressUpdate(context),
                        icon: Icon(Icons.done),
                      );
                    },
                  ),
                ],
              ),
              body: _ScrollWidget(
                needVerifyCode: args.needVerifyCode,
              ),
            ),
          );
        },
      ),
    );
  }

  void _addressUpdate(BuildContext context) async {
    if (Form.of(context).validate()) {
      AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
      ViewState viewState = await addressEditModel.addressUpdate();
      switch (viewState) {
        case ViewState.error:
          EasyLoading.showToast(addressEditModel.errorMessage);
          break;
        default:
          Navigator.of(context).pop(true);
          break;
      }
    }
  }
}

class _ScrollWidget extends StatelessWidget {
  final bool needVerifyCode;

  const _ScrollWidget({
    Key key,
    @required this.needVerifyCode,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var textStyle = TextStyle(
      color: Colors.black87,
      fontSize: 14,
    );

    var inputDecoration = InputDecoration(
      hintStyle: TextStyle(color: Colors.black54),
      border: InputBorder.none,
    );

    AddressUpdateModel addressEditModel = Provider.of(context, listen: false);

    return SingleChildScrollView(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Column(
          children: <Widget>[
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.linkMan ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '收货人',
                ),
                style: textStyle,
                onChanged: (value) {
                  addressEditModel.linkMan = value;
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入收货人';
                },
              ),
            ),
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.contactPhone ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '手机号码',
                ),
                style: textStyle,
                keyboardType: TextInputType.phone,
                onChanged: (value) {
                  addressEditModel.contactPhone = value;
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入手机号码';
                },
              ),
              // 如果不需要验证码就隐藏获取验证码按钮
              trailing: needVerifyCode
                  ? Consumer<AddressSmsModel>(
                      builder: (context, model, child) {
                        switch (model.viewState) {
                          case ViewState.busy:
                            return FlatButton(
                              onPressed: null,
                              child: SizedBox(
                                width: 12,
                                height: 12,
                                child: CircularProgressIndicator(),
                              ),
                            );
                          case ViewState.success:
                            return FlatButton(
                              onPressed: null,
                              child: CountDownText(
                                function: () {
                                  AddressSmsModel model = Provider.of(context, listen: false);
                                  model.viewState = ViewState.idle;
                                },
                                style: textStyle.copyWith(
                                  color: Colors.grey,
                                ),
                              ),
                            );
                          default:
                            return FlatButton(
                              onPressed: () => _reqCode(context),
                              child: Text(
                                '获取验证码',
                                style: textStyle,
                              ),
                            );
                        }
                      },
                    )
                  : null,
            ),
            if (needVerifyCode)
              ListTile(
                title: TextFormField(
                  decoration: inputDecoration.copyWith(
                    hintText: '验证码（未修改手机号码，则无须填写）',
                  ),
                  style: textStyle,
                  onChanged: (value) {
                    addressEditModel.verifyCode = value;
                  },
                  validator: (value) {
                    AddressUpdateModel model = Provider.of(context, listen: false);
                    return model.address?.contactPhone == model.contactPhone || value.isNotEmpty
                        ? null
                        : '请输入验证码';
                  },
                ),
              ),
            ListTile(
              title: Text(
                addressEditModel.provCityCounty ?? '所在地区',
                style: textStyle,
              ),
              trailing: Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey,
              ),
              onTap: () async {
                var result = await Navigator.of(context).pushNamed(
                  AddressRegionPage.routeName,
                  arguments: AddressRegionArgs(0, null),
                );
                debugPrint('result = $result');
                if (result != null) {
                  AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
                  addressEditModel.mapEntry = result;
                }
              },
            ),
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.detailAddress ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '详细地址：如街道、门牌号、小区、楼栋号、单元室等',
                ),
                style: textStyle,
                maxLines: 3,
                onChanged: (value) {
                  addressEditModel.detailAddress = value.trim();
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入详细地址';
                },
              ),
            ),
            SwitchListTile(
              value: addressEditModel.defaulted,
              onChanged: (value) {
                addressEditModel.defaulted = value;
              },
              title: Text(
                '设为默认',
                style: textStyle,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _reqCode(BuildContext context) async {
    AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
    AddressSmsModel addressSmsModel = Provider.of(context, listen: false);
    ViewState viewState = await addressSmsModel.addressSms(addressEditModel.contactPhone);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(addressSmsModel.errorMessage);
        break;
      default:
        // 更新code
        addressEditModel.encryptedCode = addressSmsModel.data;
        EasyLoading.showToast('发送成功');
        break;
    }
  }
}
